package com.rc.evcharger.component;

import com.rc.evcharger.common.utils.DateHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * ID生成器
 * Created by sven on 2019/11/12
 */
@Component
public class UidGenerator {
    //枪号默认长度14位
    private static final int GUNNO_LENGTH = 14;

    /**
     * 统一生成充电订单号
     * @param gunNo
     * @return
     */
    public synchronized String genChargeOrderNum(String gunNo) {
        if (StringUtils.isBlank(gunNo)) {
            return null;
        }

        //枪编号不足补0
        //if (gunNo.length() < UidGenerator.gunNoLength) {
        //    while (gunNo.length() < gunNoLength) {
        //        gunNo = gunNo + "0";
        //    }
        //}

        //枪编号超长,截取后14位
        //if (gunNo.length() > GUNNO_LENGTH) {
        //    gunNo = gunNo.substring(GUNNO_LENGTH - 14, GUNNO_LENGTH);
        //}

        if (gunNo.length() < GUNNO_LENGTH) {//枪编号不足后面补0
            gunNo = StringUtils.rightPad(gunNo, GUNNO_LENGTH, "0");
        } else if (gunNo.length() > GUNNO_LENGTH) { //枪编号超长,截取后14位
            gunNo = StringUtils.right(gunNo, GUNNO_LENGTH);
        }

        //编码规则(30位):14位枪号 + 12位日期时间 + 4位随机数
        StringBuffer orderNum = new StringBuffer(gunNo);
        orderNum.append(DateHelper.dataToString(new Date(), DateHelper.DATE_FORMAT_YYMMDDHHMMSS));
        orderNum.append(String.format("%04d", (int) (Math.random() * 1000)));

        return orderNum.toString();
    }


    /**
     * 统一生成充电订单号
     * @param 前缀
     * @return
     */
    public synchronized String genDiscountOrderNum(String prefix) {
        //编码规则(30位):14位枪号 + 12位日期时间 + 4位随机数
        StringBuffer orderNum = new StringBuffer("Y");
        orderNum.append(DateHelper.dataToString(new Date(), DateHelper.DATE_FORMAT_YYMMDDHHMMSS));
        orderNum.append(String.format("%04d", (int) (Math.random() * 1000)));

        return orderNum.toString();
    }



    public static void main(String[] args) {
        String gunNo = "69441200002154";
        if (gunNo.length() < GUNNO_LENGTH) {
            while (gunNo.length() < GUNNO_LENGTH) {
                gunNo = "0" + gunNo;
            }
        }
        if (gunNo.length() > GUNNO_LENGTH) {
            gunNo = gunNo.substring(GUNNO_LENGTH - 14, GUNNO_LENGTH);
        }

        System.out.println(gunNo + " " + gunNo.length());
    }
}
